//
//  AddMoodViewController.swift
//  MoodDiary
//
//  Created by MoodDiary on 2020/11/30.
//

import UIKit
import SVProgressHUD

class AddMoodViewController: UIViewController{
    
    @IBOutlet weak var imgV: UIImageView!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var pageControl: UIPageControl!
    
    @IBOutlet weak var btn: UIButton!
    
    @IBOutlet weak var btmView: UIView!
    @IBOutlet weak var timeLabel: UILabel!
    
    var isBadXinqing: Bool = false
    
    var selectIndex: Int?
    
    var dayStr = "今天"
    var needShowCalender = false
    
    let datePicker = CustomDatePicker(frame: CGRect(x: 0, y: 0, width: screen_width, height: screen_height), startTimeStr: "2021-1-1", currentPosition: .positionCenter)
    
    var tempDataArr:[[String:Any]] = AppConstant.feelingDatasArr
    var moodArray:[[[String:Any]]] = [[[String:Any]]]()
        
    var diaryModel: DiaryModel?
    
    var selectYear: Int = Int(NSString.currentYear()) ?? 0
    var selectDateTimeStamp: String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if let vcs = navigationController?.viewControllers {
            if vcs.count - 2 >= 0 {
                if vcs[vcs.count - 2] is AddWeatherViewController {
                    btmView.isHidden = true
                }
            }
        }
        
        selectIndex = 0
        self.configFeelingArr()
        
        btn.layer.borderWidth = 0.5
        btn.layer.borderColor = UIColor.hexColor(hex: "#8f8f8f").cgColor
        btn.layer.cornerRadius = btn.height * 0.5
        btn.layer.masksToBounds = true

        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UINib(nibName: "AddWeatherCollectionViewCell", bundle: .main), forCellWithReuseIdentifier: "AddWeatherCollectionViewCell")
        
        collectionView(collectionView, didSelectItemAt: IndexPath(row: 0, section: 0))
        
        if navigationController?.viewControllers.count ?? 0 > 1 {
            
        } else {
            navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "关闭"), style: .plain, target: self, action: #selector(closeAction))
        }
        
        if self.needShowCalender {
            self.addDatePickerFunc()
        }
        
        if let timeStamp = self.diaryModel?.timeStampStr {
            self.setDateLabel(timeStamp: timeStamp)
        }
        

        
        let tap = UITapGestureRecognizer(target: self, action: #selector(tap(r:)))
        
        btmView.isUserInteractionEnabled = true
        btmView.addGestureRecognizer(tap)

         
    }
    
    @objc func tap(r: UITapGestureRecognizer) {
               
        self.addDatePickerFunc()
    }
    
    
    func configFeelingArr(){
        
        if var imgArray = UserDefaults.standard.array(forKey: KUSERFeelingImagesArrName ) as? [[String:Any]] {
            
            if let imgDeletedArray = UserDefaults.standard.array(forKey: KUSERFeelingDeletedImagesArrName) as? [[String:Any]] {
                
                imgArray.append(contentsOf: imgDeletedArray)
            }
            
            tempDataArr = imgArray
        }else{
            
            UserDefaults.standard.setValue(tempDataArr, forKey: KUSERFeelingImagesArrName)
            UserDefaults.standard.synchronize()
        }
        
        let tempCount = tempDataArr.count%6
        
        if tempCount == 0 {
            return
        }else{
            
            for _ in 0..<(6-tempCount) {
                
                tempDataArr.append(["imgName":"","text":"","isCustom":false])
            }
        }
        
        for i in 0..<(tempDataArr.count/6) {
            
            let arr:[[String:Any]] = Array(tempDataArr[(i*6)...((i+1)*6-1)])
            moodArray.append(arr)
        }
        
    }
    
    func addDatePickerFunc() {
        
        datePicker.dateType = .year_month_day
        datePicker.delegate = self
        view.addSubview(datePicker)
        
    }
    
    // 友盟页面统计
    override func viewWillAppear(_ animated: Bool)
    {
        super.viewWillAppear(animated)
        
        btn.isUserInteractionEnabled = true
        MobClick.beginLogPageView("添加心情")
        MobClick.event("pages_num", attributes: ["TianJiaXinQing":"进入添加心情"])
    }
    
    override func viewWillDisappear(_ animated: Bool)
    {
        super.viewWillDisappear(animated)
        MobClick.endLogPageView("添加心情")
        MobClick.event("pages_num", attributes: ["TianJiaXinQing":"离开添加心情"])
    }
    
    @objc func tapBtmView() {
        
        let pickerView = UIPickerView(frame: CGRect(x: 0, y: 70.0, width: 260.0, height: 240.0))
        pickerView.delegate = self
        pickerView.dataSource = self
        
        DispatchQueue.main.async { [weak self] in
            
            guard let self = self else { return }
            
            var day2 = 0
            
            var currentYear: Int = Int(NSString.currentYear()) ?? 0
            
            if self.selectDateTimeStamp != nil {
                currentYear = Int(NSString.getYear(self.selectDateTimeStamp!)) ?? 0
            }
            
            if (currentYear % 100 == 0 && currentYear % 400 == 0) || (currentYear % 100 != 0 && currentYear % 4 == 0) {
                day2 += 29
            } else {
                day2 += 28
            }
            
            var days = 0
            
            var currentMonth: Int = Int(NSString.currentMonth()) ?? 0
            var currentDay: Int = Int(NSString.currentDay()) ?? 0
            
            if self.selectDateTimeStamp != nil {
                currentMonth = Int(NSString.getMonth(self.selectDateTimeStamp!)) ?? 0
                currentDay = Int(NSString.getDay(self.selectDateTimeStamp!)) ?? 0
            }
            
            switch currentMonth {
            case 1:
                days = currentDay
            case 2:
                days = 31 + currentDay
            case 3:
                days = 31 + day2 + currentDay
            case 4:
                days = 31 + day2 + 31 + currentDay
            case 5:
                days = 31 + day2 + 31 + 30 + currentDay
            case 6:
                days = 31 + day2 + 31 + 30 + 31 + currentDay
            case 7:
                days = 31 + day2 + 31 + 30 + 31 + 30 + currentDay
            case 8:
                days = 31 + day2 + 31 + 30 + 31 + 30 + 31 + currentDay
            case 9:
                days = 31 + day2 + 31 + 30 + 31 + 30 + 31 + 31 + currentDay
            case 10:
                days = 31 + day2 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + currentDay
            case 11:
                days = 31 + day2 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + currentDay
            case 12:
                days = 31 + day2 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + currentDay
            default:
                break
            }
            
            if currentYear == Int(NSString.currentYear()) ?? 0 {
                pickerView.selectRow(0, inComponent: 0, animated: false)
            } else {
                pickerView.selectRow(1, inComponent: 0, animated: false)
            }
            
            pickerView.selectRow(days - 1, inComponent: 1, animated: false)
        }
        
        let alertC = UIAlertController(title: "提示", message: "请选择时间\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", preferredStyle: .alert)
        alertC.view.addSubview(pickerView)
        alertC.addAction(UIAlertAction(title: "确定", style: .default, handler: { [weak self] (_) in
            let selectRow1 = pickerView.selectedRow(inComponent: 1)
            let selectRow0 = pickerView.selectedRow(inComponent: 0)
            
            let currentSelectYear = selectRow0 == 0 ? NSString.currentYear() : "\(Int(NSString.currentYear())! - 1)"
            let monthDayStr: String = self?.getMonthAndDay(row: selectRow1) ?? ""
            let timeStr = "\(currentSelectYear)" + "年" + monthDayStr + " " + NSString.currentHour() + ":" + NSString.currentMinute() + ":" + NSString.currentSecond()
            let timeStamp = NSString.convertTime(toTimeStamp2: timeStr)
            
            print(timeStr)
            print(timeStamp)
            
            if timeStamp > NSString.currentTimeStamp() {
                SVProgressHUD.showError(withStatus: "不可以选择今天之后的日期")
                SVProgressHUD.dismiss(withDelay: 2.0)
                return
            }
            
            self?.selectDateTimeStamp = timeStamp
            self?.setDateLabel(timeStamp: timeStamp)
            
        }))
        alertC.addAction(UIAlertAction(title: "取消", style: .destructive, handler: { (_) in
            
        }))
        present(alertC, animated: true, completion: nil)
    }

}

extension AddMoodViewController: MDDatePickerDelegate {
    
    func confirmAction(date: String) {
        
        
        if date != ((NSString.currentYear() + "-" + NSString.currentMonth())) + "-" + NSString.currentDay(){
            
            dayStr = "这天"
            
            if let text = moodArray[0][0]["text"] as? String {
                btn.setTitle(dayStr + "很" + text, for: .normal)
            }
            
        }
        
        var timeStr = date
        timeStr += " "
//        diaryModel?.timeStampStr = NSString.currentTimeStamp()
        timeStr += NSString.getHourAndMinute(diaryModel?.timeStampStr ?? NSString.currentTimeStamp())
        
        let dateTitleStr = NSString.convertTimeStamp(toMH: (diaryModel?.timeStampStr)!) + " " + NSString.dateWeek(withTimeStamp: (diaryModel?.timeStampStr)!)
        timeLabel.text = dateTitleStr

        datePicker.removeFromSuperview()
    }
    func cancleAction(date: String) {
        

        dayStr = "今天"
        if let text = moodArray[0][0]["text"] as? String {
            btn.setTitle(dayStr + "很" + text, for: .normal)
        }
        
        var timeStr = ((NSString.currentYear() + "-" + NSString.currentMonth())) + "-" + NSString.currentDay()
        timeStr += " "
        timeStr += NSString.getHourAndMinute(NSString.currentTimeStamp())
//        diaryModel?.timeStampStr = NSString.currentTimeStamp()
        
        datePicker.removeFromSuperview()
    }
    
}

extension AddMoodViewController {
    
    @objc func closeAction() {
        dismiss(animated: true, completion: nil)
    }
    
    @IBAction func nextAction() {
        
        btn.isUserInteractionEnabled = false
//        let page = Int(collectionView.contentOffset.x / collectionView.width)
//        diaryModel?.moodStr = moodArray[page][selectIndex ?? 0]
        
        let vc = AddReasonViewController()
//        diaryModel?.timeStampStr = selectDateTimeStamp
//        if isToday((selectDateTimeStamp != nil) ? selectDateTimeStamp:"") {
//
//        } else {
//            diaryModel?.weatherStr = "晴天"
//        }
        vc.isBadXinqing = self.isBadXinqing
        vc.diaryModel = diaryModel
        navigationController?.pushViewController(vc, animated: true)
    }
    
}

extension AddMoodViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let page = Int(collectionView.contentOffset.x / collectionView.width)
        pageControl.currentPage = page
        
        selectIndex = nil
        collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let marginX = 25.0
        let itemLength = (Double(collectionView.width) - marginX * 4) / 3
        
        return CGSize(width: itemLength, height: 45.0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { UIEdgeInsets(top: 0, left: 25.0, bottom: 0, right: 25.0) }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { 25.0 }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { 25.0 }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int { moodArray.count }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { moodArray[section].count }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell: AddWeatherCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "AddWeatherCollectionViewCell", for: indexPath) as! AddWeatherCollectionViewCell
        
        if let text:String = moodArray[indexPath.section][indexPath.row]["text"] as? String {
            
            cell.label.text = text
            if text.count > 0{
                cell.shouldShow = true
            }else{
                cell.shouldShow = false
            }
        }
        
        
        cell.showLabel = true
        
        if diaryModel?.moodStr == cell.label.text {
            cell.isSelectCell = true
        } else if selectIndex == indexPath.item {
            cell.isSelectCell = true
        } else {
            cell.isSelectCell = false
        }

        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
//        for i in 0..<collectionView.numberOfItems(inSection: 0) {
//            if i == indexPath.row {
//                selectIndex = i
//                break
//            }
//        }
        selectIndex = indexPath.item
        
        collectionView.reloadData()
        
        btn.isEnabled = true
        
        if let text:String = moodArray[indexPath.section][indexPath.row]["text"] as? String{
            
            diaryModel?.moodStr = text
            
            if text  == "不知道"  {
                btn.setTitle(dayStr + "不好描述", for: .normal)
            }else{
                btn.setTitle(dayStr + "很" + text, for: .normal)
            }
            
            
            if AppConstant.badMood.contains(text){
                self.isBadXinqing = true
            }else{
                self.isBadXinqing = false
            }
                
        }
        
        btn.layer.borderColor = UIColor.black.cgColor
        
        if let imgName:String = moodArray[indexPath.section][indexPath.row]["imgName"] as? String{
            
            imgV.image = UIImage(named: imgName)
                
        }
        
        
//        let page = Int(collectionView.contentOffset.x / collectionView.width)
        
        
        
        
        
    }
    
}

extension AddMoodViewController: UIPickerViewDelegate, UIPickerViewDataSource {
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int { 2 }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 { return 2 }
        
        var days = 31 + 0 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31
        
        if (selectYear % 100 == 0 && selectYear % 400 == 0) || (selectYear % 100 != 0 && selectYear % 4 == 0) {
            days += 29
        } else {
            days += 28
        }
        
        return days
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        
        let yearStr = NSString.currentYear()
        let yearInt = Int(yearStr) ?? 0
        selectYear = row == 0 ? yearInt : yearInt - 1
        
        if component == 0 {
            pickerView.reloadComponent(1)
        }
        
//        dateTitleStr = NSString.convertTimeStamp(toMH: timeStamp!) + " " + NSString.dateWeek(withTimeStamp: timeStamp!)
//        timeLabel.text = dateTitleStr
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if component == 0 {
            let yearStr = NSString.currentYear()
            let yearInt = Int(yearStr)
            if row == 1 {
                return "\((yearInt ?? 1) - 1)年"
            }
            return "\(yearInt ?? 0)年"
        }
        return getMonthAndDay(row: row)
    }
}

extension AddMoodViewController {
    
    func getMonthAndDay(row: Int) -> String {
        
        var days = 0
        
        if (selectYear % 100 == 0 && selectYear % 400 == 0) || (selectYear % 100 != 0 && selectYear % 4 == 0) {
            days += 29
        } else {
            days += 28
        }
        
        var prefixStr = ""
        
        if row < 31 {
            prefixStr = "01月" + String(format: "%02d日", row + 1)
        } else if row < 31 + days {
            prefixStr = "02月" + String(format: "%02d日", row + 1 - 31)
            
            print("prefixStr === \(prefixStr)")
            
        } else if row < 31 + days + 31 {
            prefixStr = "03月" + String(format: "%02d日", row + 1 - 31 - days)
        } else if row < 31 + days + 31 + 30 {
            prefixStr = "04月" + String(format: "%02d日", row + 1 - 31 - days - 31)
        } else if row < 31 + days + 31 + 30 + 31 {
            prefixStr = "05月" + String(format: "%02d日", row + 1 - 31 - days - 31 - 30)
        } else if row < 31 + days + 31 + 30 + 31 + 30 {
            prefixStr = "06月" + String(format: "%02d日", row + 1 - 31 - days - 31 - 30 - 31)
        } else if row < 31 + days + 31 + 30 + 31 + 30 + 31 {
            prefixStr = "07月" + String(format: "%02d日", row + 1 - 31 - days - 31 - 30 - 31 - 30)
        } else if row < 31 + days + 31 + 30 + 31 + 30 + 31 + 31 {
            prefixStr = "08月" + String(format: "%02d日", row + 1 - 31 - days - 31 - 30 - 31 - 30 - 31)
        } else if row < 31 + days + 31 + 30 + 31 + 30 + 31 + 31 + 30 {
            prefixStr = "09月" + String(format: "%02d日", row + 1 - 31 - days - 31 - 30 - 31 - 30 - 31 - 31)
        } else if row < 31 + days + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 {
            prefixStr = "10月" + String(format: "%02d日", row + 1 - 31 - days - 31 - 30 - 31 - 30 - 31 - 31 - 30)
        } else if row < 31 + days + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 {
            prefixStr = "11月" + String(format: "%02d日", row + 1 - 31 - days - 31 - 30 - 31 - 30 - 31 - 31 - 30 - 31)
        } else if row < 31 + days + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31 {
            prefixStr = "12月" + String(format: "%02d日", row + 1 - 31 - days - 31 - 30 - 31 - 30 - 31 - 31 - 30 - 31 - 30)
        }
        return prefixStr
    }

}

extension AddMoodViewController {
    func setDateLabel(timeStamp: String? = nil) {
        
        selectYear = Int(NSString.getYear(timeStamp ?? "")) ?? 0
        
        if selectYear == 0 {
            selectYear = Int(NSString.currentYear()) ?? 0
        }
        
        var dateTitleStr = ""
        
        if timeStamp != nil {
            dateTitleStr = NSString.convertTimeStamp(toMH: timeStamp!) + " " + NSString.dateWeek(withTimeStamp: timeStamp!)
            timeLabel.text = dateTitleStr
            
            let text = btn.titleLabel!.text!
            let index = text.index(text.startIndex, offsetBy: 2)
            let result = text.substring(from: index)
            if isToday(timeStamp!) {
                btn.setTitle("今天" + result, for: .normal)
                dayStr = "今天"
            } else {
                btn.setTitle("这天" + result, for: .normal)
                dayStr = "这天"
            }
        }
        
        
    }
    
    func isToday(_ timeStamp: String) -> Bool {
        let mYear = NSString.getYear(timeStamp) == NSString.getYear(NSString.currentTimeStamp())
        let mMonth = NSString.getMonth(timeStamp) == NSString.getMonth(NSString.currentTimeStamp())
        let mDay = NSString.getDay(timeStamp) == NSString.getDay(NSString.currentTimeStamp())
        return mYear && mMonth && mDay
    }
}
